package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserRedisServiceImpl implements IUserRedisService {

    /**
     * template:缓存模板对象
     */
    @Autowired
    private StringRedisTemplate template;

    /**
     * 缓存方法
     * @param phone:手机号
     * @param code:验证码
     */
    @Override
    public void setVerifyCode(String phone, String code) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        template.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }


    /**
     * 获取缓存中的验证码
     *
     * @param phone :手机号
     */
    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        return template.opsForValue().get(key);

    }


    //设置token令牌
    @Override
    public String setToken(UserInfo user) {
        //创建令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //把token作为key,用户对象作为value存入redis中
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        String value = JSON.toJSONString(user);
        //设置token的有效时间为30分钟
        template.opsForValue().set(key, value, RedisKeys.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }


    //通过token获取登录用户对象
    @Override
    public UserInfo getUserByToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        if (template.hasKey(key)) {
            String value = template.opsForValue().get(key);
            //JSON数据解析成对象,类型
            UserInfo userInfo = JSON.parseObject(value, UserInfo.class);
            //重置token有效时间
            template.expire(key, RedisKeys.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
            return userInfo;
        }
        return null;

    }

}
